package com.spring.service.impl;

import com.spring.annotation.Autowired;
import com.spring.annotation.Service;
import com.spring.annotation.Transactional;
import com.spring.dao.AccountDao;
import com.spring.pojo.Account;
import com.spring.service.TransferService;

/**
 * @author SpringWang
 * @date 2021/5/19
 */
@Service
public class TransferServiceImpl implements TransferService {

    @Autowired
    private AccountDao accountDao;


    @Override
    @Transactional
    public void transfer(String fromCardNo, String toCardNo, int money) throws Exception {
        Account from = accountDao.findByCardNo(fromCardNo);
        Account to = accountDao.findByCardNo(toCardNo);

        checkFromBalance(from.getBalance(), money);
        from.setBalance(from.getBalance() - money);
        to.setBalance(to.getBalance() + money);

        accountDao.updateBalanceByCardNo(from);
        accountDao.updateBalanceByCardNo(to);
    }

    private void checkFromBalance(Integer balance, int money) {
        if (balance < money) {
            throw new IllegalStateException("您余额不足！");
        }
    }
}
